% read data from TRC file into a 3-D matrix
% bryan conrad
% 2/20/2007
% returns f (the number of frames) as well as the full data set extracted
% from the TRC
% USAGE: [frames MkrData mkrName rate Header]=marker_data_read([TRC_path]);
%   if TRC_path is not specified, then a dialog will open to allow the user
%   to select a file.
%
%   format for MkrData is: datam(frame, marker, [x, y, z])

function [frames MkrData mkrName rate Header]=marker_data_read(varargin)

if nargin < 1
    % user did not specify an path, give a dialog to do so
    % this will store the last path name in the main app data structure
    lastPath = getappdata(0, 'lastPath');
    if isempty(lastPath); lastPath = 'C:\'; end;
    [name, pathstr] = uigetfile('*.trc', 'Pick TRC file to open', lastPath);
    if pathstr == 0
        disp('No file was selected, exiting.')
        return
    end
    setappdata(0, 'lastPath', pathstr);
    filename = fullfile(pathstr,name);
    disp(['Opening file: ' name])
elseif nargin == 1
    % user specified a path to a TRC file
    % break down input file name
    filename = varargin{1};
    [pathstr, name, ext, versn] = fileparts(filename);
elseif nargin > 1
    % i do not know what to do with this many parameters
    disp('ERROR: This function expects 0 or 1 arguments.')
    return
end

[data, Header]=xlsread(filename);
rate=data(3,1);
frames=data(3,3);
nMkrs=data(3,4);
nMkrsDefined = (size(data,2)-2)/3;
for i=1:nMkrs
    mkrName(i)=Header(4,i*3);
end

% Initialize marker data array
MkrData(frames,nMkrsDefined,3) = 0;

for k=1:frames                  %k: frame loop
	for j=1:nMkrsDefined        %j: marker loop (not all markers may be tracked in which case, size(data,2)<nMkrs)
            for i=1:3           %i: dimension loop
                MkrData(k,j,i)=data(k+6,j*3+(i-1));
            end;   
	end;
end;
return;
